package com.acceptable.qucun.user.aspect;

import com.acceptable.qucun.generic.util.AspectUtil;
import com.acceptable.qucun.generic.util.CodeUtil;
import com.acceptable.qucun.generic.util.result.error.UserErrorResult;
import com.acceptable.qucun.generic.util.verify.FormatVerifyUtil;
import com.acceptable.qucun.user.entity.User;
import com.acceptable.qucun.user.exception.UserOperationException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Component
@Order(10)
public class AccountBoundAspect {

    @Pointcut("execution(* com.acceptable.qucun.*.service.*Service.*Bound*(..) )")
    public void boundValid(){}

    @Pointcut("execution(* com.acceptable.qucun.user.service.UserService.*Unbound*(..) )")
    public void unboundValid(){}

    private User getUser(JoinPoint joinPoint){
        User user = null;
        Map<String, Object> paramMap = AspectUtil.paramMap(joinPoint);
        if (FormatVerifyUtil.mapIsEmpty(paramMap))
            return user;

        Map<String, String> dataMap = (Map<String, String>) paramMap.get("HashMap");
        if (FormatVerifyUtil.mapIsEmpty(dataMap))
            return user;

        Map<String, Object> userMap = (Map<String, Object>) CodeUtil.string2Object(dataMap.get("user"));
        if (FormatVerifyUtil.mapIsEmpty(userMap))
            return user;

        user = CodeUtil.map2Object(userMap, User.class);
        return user;
    }

    @Before(value = "boundValid()")
    public void boundAccountIsValid(JoinPoint joinPoint){
        User user = this.getUser(joinPoint);
        if (user == null)
            throw new UserOperationException(UserErrorResult.EMAIL_NOT_BOUND_ERROR);
    }

    @Before(value = "unboundValid()")
    public void unboundAccountIsValid(JoinPoint joinPoint){
        User user = this.getUser(joinPoint);
        if (user != null)
            throw new UserOperationException(UserErrorResult.EMAIL_NOT_BOUND_ERROR);
    }
}
